/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.pig.pigpen.actions;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import org.apache.hadoop.conf.Configuration;
import org.apache.pig.ExecType;
import org.apache.pig.PigServer;
import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil;
import org.apache.pig.impl.PigContext;
import org.apache.pig.pigpen.ConsoleLogger;
import org.apache.pig.pigpen.PigPenActivator;
import org.apache.pig.pigpen.LoggerUtil;
import org.apache.pig.pigpen.PluginConfiguration;
import org.apache.pig.pigpen.editor.PigPenEditor;
import org.apache.pig.pigpen.editor.parser.OperatorInfo;
import org.apache.pig.pigpen.editor.parser.SimpleQueryParser;
import org.apache.pig.pigpen.preferences.PreferenceConstants;
import org.apache.pig.pigpen.util.PigServerPool;
import org.apache.pig.pigpen.view.ExampleData;
import org.apache.pig.pigpen.view.ExampleTreeViewer;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.FileEditorInput;

public class LaunchExampleGenerator implements IWorkbenchWindowActionDelegate {

    private ISelection selection;
    IWorkbenchWindow window;
    PigServer pigServer;

    // private static final String JOB_TRACKER_LOCATION = "mapred.job.tracker";
    // private static final String FILE_SYSTEM_LOCATION = "fs.default.name";

    private ConsoleLogger logger = ConsoleLogger.getDefault();

    public void dispose() {
        // TODO Auto-generated method stub

    }

    // private boolean initPigServer() {
    // IPreferenceStore store = EclipsePlugin.getDefault().getPreferenceStore();
    // String stringList = store.getString(PreferenceConstants.P_PROPERTIES);
    // Map<String, String> PrefProperties =
    // PluginConfiguration.parseString(stringList);
    // String confPath = PrefProperties.get(PreferenceConstants.P_CONFPATH);
    //        
    // if(confPath == null) {
    // logger.clear();
    // logger.setFocus();
    // logger.error(
    // "Please set the ConfigurationPath variable in Pig Preferences (Window -> Preferences -> Pig) to point to the directory containing hadoop-site.xml and pig.properties"
    // );
    // return false;
    // }
    // logger.clear();
    // if(confPath.charAt(confPath.length() - 1) != '/')
    // confPath = confPath + "/";
    //        
    // try {
    //            
    // FileInputStream input = new FileInputStream(new File(confPath +
    // "pig.properties"));
    // Properties sysProperties = new Properties();
    // sysProperties.load(input);
    // for(Entry<Object, Object> e : sysProperties.entrySet()) {
    // System.setProperty((String)e.getKey(), (String)e.getValue());
    // }
    // Configuration conf = new Configuration();
    // conf.addResource((new File(confPath +
    // "hadoop-site.xml")).toURI().toURL());
    //            
    // Properties properties = ConfigurationUtil.toProperties(conf);
    //            
    // pigServer = new PigServer(ExecType.MAPREDUCE, properties);
    //            
    //            
    // //System.out.println(pigContext.getDfs().getStatistics().toString());
    // } catch (Throwable e) {
    // //logger.setFocus();
    // logger.error(e.getMessage());
    // logger.error(
    // "Please set the ConfigurationPath variable in Pig Preferences (Window -> Preferences -> Pig) to point to the directory containing hadoop-site.xml and pig.properties"
    // );
    // }
    // PigContext pigContext = pigServer.getPigContext();
    // //logger.setFocus();
    // logger.info("Connected to map-reduce job tracker at: " +
    // pigContext.getProperties().getProperty(JOB_TRACKER_LOCATION));
    // logger.info("Connected to hadoop file system at: " +
    // pigContext.getProperties().getProperty(FILE_SYSTEM_LOCATION));
    // return true;
    // }

    public void init(IWorkbenchWindow window) {
        // TODO Auto-generated method stub
        this.window = window;

        // initPigServer();
        pigServer = PigServerPool.getPigServer();
    }

    public void run(IAction action) {

        IWorkbenchPage page = PlatformUI.getWorkbench()
                .getActiveWorkbenchWindow().getActivePage();

        // figure out what file is selected
        // IFile file = ActionDelegateHelper.GetSelectedFile(selection);
        IFile file = ((FileEditorInput) window.getActivePage()
                .getActiveEditor().getEditorInput()).getFile();
        // IFile temp = null;
        if (file == null)
            return;

        OperatorInfo info = null;
        // try {
        // BufferedReader input = new BufferedReader(new
        // InputStreamReader(file.getContents()));
        //            
        // for(String str = input.readLine(); str != null; str =
        // input.readLine()) {
        // if("".equals(str))
        // continue;
        // info = doSimpleParsing(str);
        // pigServer.registerQuery(str);
        // }
        // } catch (Exception e) {
        // logger.error(e.getMessage());
        // }

        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(
                    file.getContents()));
            StringBuffer query = new StringBuffer();
            for (String str = input.readLine(); str != null; str = input
                    .readLine())
                query.append(str);

            String[] queries = query.toString().split(";");

            for (int i = 0; i < queries.length; i++) {
                String q = queries[i].trim();
                if ("".equals(q) || q.toLowerCase().startsWith("store")
                        || q.toLowerCase().startsWith("describe")
                        || q.toLowerCase().startsWith("illustrate"))
                    continue;
                info = doSimpleParsing(q + ";");
                pigServer.registerQuery(q + ";");
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        // see if there's a pre-existing view instance for this file
        IViewReference viewRef = ActionDelegateHelper.GetLauncherReference(
                page, file, ActionDelegateHelper.VIEW.EXAMPLEVIEW);
        boolean viewInstanceAlreadyExisted = (viewRef != null);

        // create a new instance of the launch view
        if (!viewInstanceAlreadyExisted) {
            try {
                ActionDelegateHelper.ShowLauncher(page, file,
                        ActionDelegateHelper.VIEW.EXAMPLEVIEW);
                viewRef = ActionDelegateHelper.GetLauncherReference(page, file,
                        ActionDelegateHelper.VIEW.EXAMPLEVIEW);
            } catch (PartInitException e) {
                LoggerUtil.logError("Error creating launch window", e);
            }
        }

        // tell the view to go ahead and launch the file

        ExampleTreeViewer view = (ExampleTreeViewer) viewRef.getView(true);
        logger.info("Ready to run the example generator");

        view.setInput(new ExampleData(pigServer.getExamples(info.outputAlias)));

        logger.info("Examples generated");
        view.setFocus();
        // try {
        // view.setInput(new
        // ExampleData(pigServer.getExamples(pigServer.getAliases
        // ().get(info.outputAlias))));
        // } catch (IOException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

    }

    private OperatorInfo doSimpleParsing(String cmd) {
        // use basic parsing to get alias + op name
        InputStream stream = new ByteArrayInputStream((cmd + "\n").getBytes());
        SimpleQueryParser simpleParser = new SimpleQueryParser(stream);
        OperatorInfo opInfo = null;
        try {
            opInfo = simpleParser.Parse();
        } catch (Throwable e) {
            // ignore
        }

        try {
            stream.close();
        } catch (IOException e) {
            // just ignore
        }

        return opInfo;
    }

    public void selectionChanged(IAction action, ISelection selection) {
        // TODO Auto-generated method stub
        this.selection = selection;

    }

    private class runExampleGenerator implements Runnable {

        public void run() {
            // TODO Auto-generated method stub

        }

    }

}
